package edu.ncut.vod.jsf.examonline.selfmadevalidator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

public class ManagerNameValidator implements Validator {

    /**
     * validate field 'managerName':its length can not be long than 12
     */
    public void validate(FacesContext arg0, UIComponent component, Object obj)
            throws ValidatorException {
        debug("method validate in class ManagerNameValidator is called");

        String label = ((HtmlInputText) component).getLabel();

        if("managerName".equals(label)){
            String fieldValue = (String) obj;   // get the value of field which needs validating

            // validate field 'humanId':it must be number or English letter
            if(fieldValue.length() > 12){
                FacesContext facesContext = FacesContext.getCurrentInstance();
                FacesMessage msg=MessageFactory.getMessage(facesContext,"managerNameLength_smaller","managerNameLength_smaller");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                /*
                 * public abstract void addMessage(java.lang.String clientId,FacesMessage message)
                 * Append a FacesMessage to the set of messages associated with the specified client
                 * identifier, if clientId is not null. If clientId is null, this FacesMessage is
                 * assumed to not be associated with any specific component instance.
                 * Parameters:clientId - The client identifier with which this message is associated
                 *                  (if any)
                 *            message - The message to be appended
                 */
                facesContext.addMessage("login:managerName",msg);
                throw new ValidatorException(msg);
            }
        }
    }

    /**
     * print message on console
     * @param message
     */
    public void debug(String message){
        System.out.println(message);
    }
}
